import React from "react";

import {Card,Divider,Radio,Checkbox,Row,Col,Table,List,InputNumber,Select, Input,Button} from 'antd';

import { ajax,batchAjax, inArray,openErrorNotification, openSuccessNotification, openInfoNotification,showResultMessage, isEmpty,isNotNull, isNull } from '../common';

import styled from '@emotion/styled';

import UIActionBar from '../uicomponents/UIActionBar';

import UIIcon from '../uicomponents/UIIcon';

import UIToolbar from '../uicomponents/UIToolbar';

import UIFormView from '../uicomponents/UIFormView';

import BusinessNodeFormConfigPanel from './BusinessNodeFormConfigPanel';

//mport DemoCanvasWidget  from './DemoCanvasWidget'

import createEngine, { 
    DefaultLinkModel, 
    DefaultNodeModel,
    DiagramModel 
} from '@projectstorm/react-diagrams';

import { CanvasWidget } from '@projectstorm/react-canvas-core';
import UIView from "../uicomponents/UIView";


/** 
 *  业务流程配置管理
*/
export default class BusinessProcessConfigPanel extends React.Component {
	constructor(props) {
        super(props);

        const engine = createEngine();

        const diagramModel = new DiagramModel();

        diagramModel.setGridSize(50);

        engine.setModel(diagramModel);
        
		this.state = {
            formTitle: "",
            engine : engine,
            model : diagramModel,
		}
    }

    componentDidMount(){

        const {engine,model} = this.state;

        const {diagramListener} = this;

        const businessProcess = this.props.location.state.process;

        const diagramToolbar = this.diagramToolbar;

        diagramToolbar.setEnable("delete",true);

        diagramToolbar.setEnable("configNodeForm",true);

        ajax('COE/businessProcessDiagram/query', {businessProcessId : businessProcess.id}, (data) => {
            
            if(data.total > 0){
                model.deserializeModel(JSON.parse(data.records[0].businessProcessDiagram), engine);
                engine.setModel(model);
                engine.repaintCanvas();

                const entities = model.getNodes();

                entities.forEach(node => {
                    node.registerListener({
                        eventDidFire : (event) => { diagramListener(event) },
                    });
                });
            }
        });

    }

    diagramListener = (event) => {

        const diagramToolbar = this.diagramToolbar;

        if(event.function === "selectionChanged"){
            diagramToolbar.setEnable("delete",!event.isSelected);
            diagramToolbar.setEnable("configNodeForm",!event.isSelected);
        }
    }

    actionHandler = (actionEvent) => {

        const {engine,model} = this.state;

        const {diagramListener} = this;

        const businessProcess = this.props.location.state.process;

        return {
			doSave: () => {

                const { nodeFormRef } = this;
		
                nodeFormRef.getFormData((formData) => {

                    const node1 = new DefaultNodeModel({
                        name: formData.businessNodeName,
                        color: 'rgb(0,192,255)',
                        businessNodeType: formData.businessNodeType,
                        remarks : formData.remarks,
                    });
                    
                    node1.setPosition(100, 100);
                    node1.addOutPort('输出').setMaximumLinks(1);
                    node1.addInPort('输入').setMaximumLinks(1);

                    node1.registerListener({
                        eventDidFire : (event) => { diagramListener(event) },
                    });
    
                    const nodeItems = model.addAll(node1);

                    nodeItems.forEach((node) => {

                        ajax('COE/businessNode/save', 
                            {
                                businessProcessId : businessProcess.id,
                                processDiagramNodeId : node.getID(),
                                businessNodeName : node.options.name,
                                businessNodeType : node.options.businessNodeType,
                                remarks : node.options.remarks,
                            }, 
                            (data) => {
                                console.log(data);
                            }
                        );
    
                    });
    
                    engine.repaintCanvas();

                    nodeFormRef.closeModal();

                    let modelStr = JSON.stringify(model.serialize());

                    ajax('COE/businessProcessDiagram/save', {businessProcessId : businessProcess.id,businessProcessDiagram : modelStr}, (data) => {
                        
                    });
                });
            },
            addNew : () => {

                const { nodeFormRef } = this;
                this.setState({ formTitle: '新增业务流程节点'});
                setTimeout(() => {
                    nodeFormRef.openModal();
                });

            },
            doDelete : () => {
                const entities = model.getSelectedEntities();

                const diagramToolbar = this.diagramToolbar;

                entities.forEach(node => {
                   
                    ajax('COE/businessNode/removeByDiagramNodeId',{diagramNodeId : node.getID()},(data) => {
                        node.remove();
                        engine.repaintCanvas();
                        let modelStr = JSON.stringify(model.serialize());

                        ajax('COE/businessProcessDiagram/save', {businessProcessId : businessProcess.id,businessProcessDiagram : modelStr}, (data) => {
                            
                        });

                        diagramToolbar.setEnable("delete",true);
                        diagramToolbar.setEnable("configNodeForm",true);
                    });
                });

            },
            saveDiagram : () => {
                let modelStr = JSON.stringify(model.serialize());

                ajax('COE/businessProcessDiagram/save', {businessProcessId : businessProcess.id,businessProcessDiagram : modelStr}, (data) => {
                    
                    showResultMessage({
                        success: true,
                        message: 'message.saveSuccess',
                    });
                });
            },
            configNodeForm : () => {
                this.nodeFromConfigPanel.openModal();
            },
        }
    }

    render() {

        const businessProcessCardProps = {
            title: <span> <UIIcon icon={'cogs'} /> {'设置 [' + this.props.location.state.process.businessProcessName + '] 流程'} </span>,
            extra: <React.Fragment><UIToolbar ref={(inst) => this.diagramToolbar = inst} actionGroupId="ProductUI:BusinessProcessDiagramActionGroup" actionHandler={this.actionHandler}/> <Divider type="vertical" /> <UIActionBar {...this.props} actionGroupId='goBackActionGroup' actionHandler={() => { }} /></React.Fragment>,
            ref : (inst) => { this. businessProcessCardRef = inst }
        };

        const nodeFormProps = {
			ref: (inst) => { this.nodeFormRef = inst },
			formConfigId: 'ProductUI:BusinessNodeForm',
			actionGroupId: 'ProductUI:saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		};

        const {engine} = this.state;

        return (
            <Card {...businessProcessCardProps} >
                <UIFormView {...nodeFormProps} />
                <CanvasWidget className="diagram-container" engine={engine} />
                <UIView ref={ (inst) => this.nodeFromConfigPanel = inst } 
                            inPop={true}
                            destroyOnClose={true}
                            title="配置表单"
                >
                    <BusinessNodeFormConfigPanel />
                </UIView>
                
            </Card>
        );
    }
}